package threads;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;

import model.Player;
import model.Preference;
import model.Settings;
import model.inventory.InventoryPlayer;
import net.HTTPDownloader;
import util.LoggingUtils;
import util.PlayerUtilities;
import cmd.RemoteCommandExecutor;

public class UpdateTester implements Runnable {

	private Player player;
	//RBB
	protected final String className = this.getClass().getName();

	public UpdateTester(Player p) {
		this.player = p;
	}

	@Override
	public void run() {
		String classMethod = className + ".run()";
		LoggingUtils.logStart(classMethod + " which should run indefinitely");
		int count = 0;
		while (true) {
			try {
				if (this.hasNewUpdate()) {
					String remoteFile = Settings.DMB_DOMAIN + "/webtool/boxdata/" + Preference.getInstance().getBoxID() + "/"
							+ Settings.RESOURCES_FILENAME;
					LoggingUtils.logStart("download of remote file " + remoteFile + " in " + classMethod);
					boolean downloaded = HTTPDownloader.getInstance().download(remoteFile, Settings.RESOURCES_FILENAME);
					// HttpRequest.postUpdateComplete();
					System.out.println("unzip");
					PlayerUtilities.unzip(new File(Settings.RESOURCES_FILENAME), new File("."));
					System.out.println("run commands");
					RemoteCommandExecutor.getInstance().executeCommands();
					System.out.println("update inventory");
					InventoryPlayer.getInstance().update();
					System.out.println("update player");
					this.player.update();
					System.out.println("download content");
					this.player.downloadContents();
					try {
						synchronized (this) {
							this.wait(10000);
						}
					} catch (InterruptedException e) {
						LoggingUtils.log(Level.SEVERE, "Cannot wait for interval 10000" 
								+ " in " + classMethod + " because it was interrupted", e);
						e.printStackTrace();
					}
				}
			} catch (MalformedURLException e) {
				LoggingUtils.log(Level.SEVERE, "Cannot update player and download its contents in " + classMethod, e);
				e.printStackTrace();
			}
		}
	}

	public boolean hasUpdate() {
		String remoteFile = Settings.DMB_DOMAIN + "/webtool/boxdata/" + Preference.getInstance().getBoxID() + "/" + Settings.RESOURCES_FILENAME;
		System.out.println(remoteFile);
		return HTTPDownloader.getInstance().download(remoteFile, "./" + Settings.RESOURCES_FILENAME);
	}

	public boolean hasNewUpdate() throws MalformedURLException {
		URL url = new URL(Settings.UPDATE_CHECKER_URL);
		String data = net.HttpPostConnector.getBoxToken() + "&reqtype=checkupdate";
		net.HttpPostConnector conn = new net.HttpPostConnector(url, data);
		conn.post();
		if (conn.getResult() != null && conn.getResult().contains("true")) {
			return true;
		} else {
			// System.out.println("Get Update Result: " + conn.getResult());
		}
		return false;
	}

}
